/**
 * @description 交易所协议式回购
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { ModalC, FirstHeaderC, SecondHeaderC, NoDataMaskC } from '../../../../comps';
import { Row, Col, message } from 'antd';
import style from './index.less';
import InstructionSend from './InstructionSend.js';
import PledgeBondsInfor from './PledgeBondsInfor.js';
import PositionAnalysis from './PositionAnalysis.js';
import RepurchaseInfor from './RepurchaseInfor.js';
import { connect } from 'dva';
import 'moment/locale/zh-cn';
@connect(({ exchangeAgreement, loading }) => ({ exchangeAgreement, loading }))
export default class ExchangeAgreement extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      columns1: [],
      dataSource1: [],
      columns2: [],
      dataSource2: [],
      select1: [],
      select2: [],
      exchange: '101',
      quotationType: '1',
      orderSide: null,
      settlementDate: null,
      repoRate: null,
      childData: [],
      addNewPledgeBondData: null,
      reNewPledgeBondData: null,
      occupationDays: null,
      spanNumber: '12',
      gutter: '20',
      portfolio: undefined, // 组合
      masking: true,
      querys: {}, //二次确认的数据
      isShow: false, //二次确认弹窗是否显示
    };
  }

  componentDidMount() {
    if (this.props.tradeInfo) {
      this.reNewPledgeBond(this.props.tradeInfo.trade13);
    }
  }

  //持仓分析 和 在途回购信息表格数据
  getTableData = (e, type) => {
    if (type == '1') {
      if (JSON.stringify(e) == '{}') {
        this.setState({
          columns1: [],
          dataSource1: [],
          select1: [],
        });
      } else {
        this.setState({
          columns1: e.columns,
          dataSource1: e.dataSource,
          select1: e.dataSource,
        });
      }
    }
    if (type == '2') {
      if (JSON.stringify(e) == '{}') {
        this.setState({
          columns2: [],
          dataSource2: [],
          select2: [],
        });
      } else {
        this.setState({
          columns2: e.columns,
          dataSource2: e.dataSource,
          select2: e.dataSource,
        });
      }
    }
  };

  //请求数据 触发表格loading
  getLoading = (type) => {
    if (type == '0') {
      this.setState({
        columns1: undefined,
        dataSource1: undefined,
        select1: [],
        columns2: undefined,
        dataSource2: undefined,
        select2: [],
      });
    }

    if (type == '1') {
      this.setState({
        columns1: undefined,
        dataSource1: undefined,
        select1: [],
      });
    }
  };

  //获取质押券信息数据 并下达指令
  getPledgeBondInfo = (type) => {
    let childData = this.state.child.getData();
    if (childData[0]?.isEdit) {
      message.error('请先保存质押券信息');
      return;
    }
    this.setState(
      {
        childData: childData,
      },
      () => {
        if (type == '1') {
          if (this.props.tradeBook == '0') {
            //指令下达二次确认
            if (this.state.isShow) {
              //请求后端
              this.state.child2.saveInstructionSend();
            } else {
              //详情展示
              const data = this.state.child2.saveInstructionSend('detail');

              if (!data) return;
              this.setState({
                querys: data,
                isShow: true,
                timeStamp: new Date().getTime(),
              });
            }
          } else {
            //簿记下达
            this.state.child2.saveInstructionSend();
          }
        }

        if (type == '2') {
          this.state.child2.remind();
        }
        if (type == 'trail') {
          this.state.child2.trialOnClicks();
        }
      },
    );
  };

  //清空质押券信息
  clearPledgeBondInfo = () => {
    this.state.child.clearData();
  };

  //（点击持仓分析-质押券代码），模态框数据回填
  addNewPledgeBond = (e) => {
    this.setState(
      {
        addNewPledgeBondData: e,
      },
      () => {
        this.state.child.addNewPledgeBondData();
      },
    );
  };

  //（点击在途回购信息-回购代码），表数据回填
  reNewPledgeBond = (e) => {
    this.setState(
      {
        reNewPledgeBondData: e,
      },
      () => {
        this.state.child.reNewPledgeBondData();
        this.state.child2.reNewPledgeBondData2();
      },
    );
  };

  //交易所切换
  changeExchange = (exchange) => {
    this.setState({
      exchange: exchange,
    });
  };

  //报价类型切换
  changeQuotationType = (e, orderSide) => {
    this.setState({
      quotationType: e,
    });
    if (orderSide) {
      this.setState({
        orderSide: orderSide,
      });
    }
  };

  //委托方向切换
  changeOrderSide = (orderSide) => {
    this.setState({
      orderSide: orderSide,
    });
  };

  //到期结算日切换
  changeSettlementDate = (settlementDate) => {
    this.setState({
      settlementDate: settlementDate,
    });
  };

  //回购利率改变
  changeRepoRate = (repoRate) => {
    this.setState({
      repoRate: repoRate,
    });
    if (repoRate) {
      // 利率改变了,更新质押券表的数据
      this.state.child.changeDataSource(repoRate);
    }
  };

  //实际占款天数改变
  changeOccupationDays = (occupationDays) => {
    this.setState({
      occupationDays: occupationDays,
    });
    if (occupationDays) {
      // 天数改变了,更新质押券表的数据
      this.state.child.changeDataSource1(occupationDays);
    }
  };

  //组合/产品切换
  getPortfolioId = (portfolioId) => {
    //调用父亲方法设置portfolioId
    this.setState({ portfolio: portfolioId });
    this.props.setPortfolioId(portfolioId);
    if (portfolioId) {
      this.setState({
        masking: false,
      });
    } else {
      this.setState({
        masking: true,
      });
    }
  };

  //二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };

  // 二次确认modal框
  showModal = () => {
    const { querys, isShow, timeStamp } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 900,
      height: 500,
      className: 'confirmOrder',
      confirmLoading: loading.effects['exchangeAgreement/saveInstruction'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={() => this.getPledgeBondInfo('1')} onCancel={this.handleCancel}>
        <InstructionSend edit={false} initValue={querys.trade13} timeStamp={timeStamp} />
      </ModalC>
    );
  };

  changeFee = (num, price) => {
    this.state.child2.changeFee('pledgedbondsamount', num ? num : undefined);
    setTimeout(() => {
      this.state.child2.changeFee('price', price ? price : undefined);
    }, 100);
  };
  //抛出投资类型
  investmentChange = () => {};
  render() {
    return (
      <div style={{ overflowX: 'hidden' }}>
        <Row gutter={this.state.gutter}>
          <Col span={this.state.spanNumber}>
            <div>
              <FirstHeaderC title='持仓分析' />
            </div>
            <div className={style.bgcolor} style={{ position: 'relative' }}>
              <PositionAnalysis
                tradeBook={this.props.tradeBook}
                columns={this.state.columns1}
                dataSource={this.state.dataSource1}
                quotationType={this.state.quotationType}
                orderSide={this.state.orderSide}
                repoRate={this.state.repoRate}
                settlementDate={this.state.settlementDate}
                addNewPledgeBond={this.addNewPledgeBond}
              />
              {this.state.masking && <NoDataMaskC height={'165px'} title={'请选择相对应的组合，加载数据！'} />}
            </div>
            <div style={{ marginTop: '55px' }}>
              <FirstHeaderC title='在途回购信息' />
            </div>
            <div className={style.bgcolor} style={{ position: 'relative' }}>
              <RepurchaseInfor tradeBook={this.props.tradeBook} columns={this.state.columns2} dataSource={this.state.dataSource2} reNewPledgeBond={this.reNewPledgeBond} />
              {this.state.masking && <NoDataMaskC height={'165px'} title={'请选择相对应的组合，加载数据！'} />}
            </div>
          </Col>
          <Col span={this.state.spanNumber}>
            <div>
              <FirstHeaderC title='交易要素' />
            </div>
            <SecondHeaderC title='质押券信息' />
            <div>
              <PledgeBondsInfor
                portfolio={this.state.portfolio}
                tradeBook={this.props.tradeBook}
                select1={this.state.select1}
                select2={this.state.select2}
                quotationType={this.state.quotationType}
                orderSide={this.state.orderSide}
                exchange={this.state.exchange}
                repoRate={this.state.repoRate}
                occupationDays={this.state.occupationDays}
                settlementDate={this.state.settlementDate}
                addNewPledgeBondData={this.state.addNewPledgeBondData}
                reNewPledgeBondData={this.state.reNewPledgeBondData}
                onRef={(ref) => this.setState({ child: ref })} // 调用子组件方法，获取质押券表数据
                type={this.props.type}
                changeFee={this.changeFee}
              />
            </div>
            <div style={{ marginTop: '10px' }}>
              <SecondHeaderC title='基本信息' />
            </div>
            <div className={style.bgcolor}>
              <InstructionSend
                type={this.props.type}
                tradeBook={this.props.tradeBook} //tradeBook:0-指令  1-簿记
                tradeInfo={this.props.tradeInfo ? this.props.tradeInfo : null}
                rehandleSearch={this.props.onCancel}
                rehandleSearch2={this.props.onOk}
                getTableData={this.getTableData}
                getLoading={this.getLoading}
                changeExchange={this.changeExchange}
                changeQuotationType={this.changeQuotationType}
                changeOrderSide={this.changeOrderSide}
                changeRepoRate={this.changeRepoRate}
                changeSettlementDate={this.changeSettlementDate}
                changeOccupationDays={this.changeOccupationDays}
                getPledgeBondInfo={this.getPledgeBondInfo}
                clearPledgeBondInfo={this.clearPledgeBondInfo}
                childData={this.state.childData}
                getPortfolioId={this.getPortfolioId} //组合id，用来切换tab获取资金
                reNewPledgeBondData={this.state.reNewPledgeBondData}
                onRef={(ref) => this.setState({ child2: ref })} // 调用子组件方法，获取质押券表数据
                onCancel={this.handleCancel}
                investmentChange={this.investmentChange}
              />
            </div>
          </Col>
        </Row>
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
      </div>
    );
  }
}
